package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.FreemarkerService;
import com.heima.common.Constants;
import com.heima.common.constants.message.Article2EsConstants;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.file.service.MinioService;
import com.heima.model.media.dtos.WmNewsContentItem;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.bouncycastle.jcajce.provider.digest.MD2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class FreemarkerServiceImpl implements FreemarkerService {

    @Autowired
    Configuration configuration;

    @Autowired
    private MinioService minioService;

    @Autowired
    @Lazy
    private ApArticleService articleService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Override
    @Async(Constants.THREAD_POOL_NAME)
    public void asyncContentStatic(Long articleId, String content) {
        //生成静态的html
        String html = createHtml(content);
        // 上传minio
        String url = uploadToMinio(articleId, html);
        // 回填url地址到ap_article
        updateArticleStaticUrl(articleId, url);
        // 给MQ发消息，通知search服务，有新的文章发布
        kafkaTemplate.send(Article2EsConstants.ARTICLE_2_ES_TOPIC, ""+articleId);
    }

    private void updateArticleStaticUrl(Long articleId, String url) {
        ApArticle toBeUpdate = new ApArticle();
        toBeUpdate.setId(articleId);
        toBeUpdate.setStaticUrl(url);
        articleService.updateById(toBeUpdate);
    }

    private String uploadToMinio(Long articleId, String html) {
        String filename = articleId + ".html";
        return minioService.uploadHtmlFile("", filename, new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)));
    }

    private String createHtml(String content) {
        StringWriter out = new StringWriter();
        List<WmNewsContentItem> wmNewsContentItems = JSON.parseArray(content, WmNewsContentItem.class);
        Map<String, Object> data = new HashMap<>();
        data.put("content", wmNewsContentItems);
        try {
            configuration.getTemplate("article.ftl").process(data, out);
            return out.toString();
        } catch (Exception e) {
            log.error("freemarker生成静态页面异常:{}", ExceptionUtils.getStackTrace(e));
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
